package com.zmn.plat.business.impl.channel.bail;

import com.zmn.common.utils.date.DateUtil;
import com.zmn.plat.business.interfaces.channel.ChannelBService;
import com.zmn.plat.business.interfaces.channel.bail.ChannelBailBService;
import com.zmn.plat.common.constant.ChannelConsts;
import com.zmn.plat.common.constant.RedisKeyConstant;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.entity.channel.bail.ChannelBail;
import com.zmn.plat.model.entity.channel.bail.ChannelBailLog;
import com.zmn.plat.services.interfaces.channel.bail.ChannelBailLogService;
import com.zmn.plat.services.interfaces.channel.bail.ChannelBailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * 描述: 渠道保证金管理
 *
 * @author jiafei
 * @version 1.0
 * @since 2021/6/16 15:10
 */
@Slf4j
@Service
public class ChannelBailBServiceImpl implements ChannelBailBService {

    @Resource
    private ChannelBailService channelBailService;

    @Resource
    private ChannelBailLogService channelBailLogService;

    @Resource
    private ChannelBService channelBService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void inOrOutBail(Integer channelId, Integer type, Integer amount, String operator, String remark) {

        ChannelBail bail = channelBailService.findById(channelId);
        if (bail == null) {
            if (type == ChannelConsts.CHANNEL_DEPOSIT_TYPE_RECHARGE) {
                bail = new ChannelBail(channelId, amount, operator, operator, DateUtil.getNow(), DateUtil.getNow());
                channelBailService.insert(bail);
            } else {
                throw new PlatException("无保证金可退!");
            }
        } else {
            if (type == ChannelConsts.CHANNEL_DEPOSIT_TYPE_REFUND || type == ChannelConsts.CHANNEL_DEPOSIT_TYPE_DEDUCTION) {
                // 退款/扣款取负数
                amount = amount * -1;
                int balance = bail.getBalance() + amount;
                if (balance < 0) {
                    throw new PlatException((type == ChannelConsts.CHANNEL_DEPOSIT_TYPE_REFUND ? "退款" : "扣款") + "金额大于当前保证余额!");
                }
                // 修改 保证金账户余额
            }
            channelBailService.updateBalance(channelId, amount);
        }
        bail = channelBailService.findById(channelId);
        ChannelBailLog bailLog = new ChannelBailLog(null, channelId, type, amount, bail.getBalance(), remark, operator, operator, DateUtil.getNow(), DateUtil.getNow());
        channelBailLogService.insert(bailLog);
        // 渠道日志
       // channelBService.createLog(channelId, null, TAB_BZJGL, null);
        // redis key 删除
        String key = RedisKeyConstant.getKeyChannelBail(channelId);
        redisTemplate.delete(key);

    }
}
